<template>
    <div>

        <el-dialog v-model="props.addDialog" title="添加角色" draggable width="50%" @close="handleClose" class="dialogs"
            @open="handleOpenDialogAdd">
            <el-form :model="rolesAdd" :rules="rulesAdd" ref="ruleFormRefAdd" label-width="100px">
                <el-row>
                    <el-col>
                        <el-form-item label="角色名称" prop="roleName" :class="{ 'bold-label': true }">
                            <el-input v-model="rolesAdd.roleName" placeholder="请输入角色名称" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="权限字符" prop="roleKey" :class="{ 'bold-label': true }">
                            <el-input v-model="rolesAdd.roleKey" placeholder="请输入权限字符" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col class="sort-col">
                        <el-form-item label="角色顺序" prop="roleSort" :class="{ 'bold-label': true }">
                            <el-input-number v-model="rolesAdd.roleSort" :min="0" controls-position="right">
                            </el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col class="status-col">
                        <el-form-item label="状态" :class="{ 'bold-label': true }">
                            <el-radio-group v-model="rolesAdd.status">
                                <el-radio value="0">正常</el-radio>
                                <el-radio value="1">停用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <!-- 授权添加 -->
                        <el-form-item label="菜单权限" :class="{ 'bold-label': true }">
                            <el-card shadow="never" body-style="">
                                <el-tree ref="tree" :data="props.treeData" node-key="menuId" :props="{
                                    children: 'children',
                                    label: 'menuName'
                                }" :show-checkbox="true"> </el-tree>
                            </el-card>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注" :class="{ 'bold-label': true }">
                            <el-input v-model="rolesAdd.remark" placeholder="请输入内容" :rows="2" type="textarea"
                                clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleSubmitAdd(ruleFormRefAdd)">确定</el-button>
                    <el-button @click="Visible">取消</el-button>
                </div>
            </template>
        </el-dialog>


    </div>
</template>

<script setup>
import { ref, nextTick, onMounted, reactive } from 'vue';
import { ElMessage } from "element-plus";
import { insertRole } from '@/apis/lth/index'
const props = defineProps(['addDialog', "treeData"])
const emit = defineEmits(['close-dialog'])

// 定义角色数据，初始化数据默认值
const rolesAdd = reactive({
    roleId: '',
    roleName: '',
    roleKey: '',
    roleSort: 0,
    status: '0',
    createTime: '',
    remark: '',
});
const ruleFormRefAdd = ref();
//定义响应式对象，用于重置表单
const resetFormAdd = reactive({ ...rolesAdd });
//验证规则对象
const rulesAdd = {
    roleName: [{
        required: true,//必填项
        message: "角色名称不能为空",//提示错误信息
        trigger: "blur"//触发验证的时机，当失去焦点时触发
    }],
    roleKey: [{
        required: true, message: "权限字符不能为空", trigger: "blur"
    }],
    roleSort: [{
        required: true, message: "角色顺序不能为空", trigger: "blur"
    }]
};
//打开对话框的处理函数
const handleOpenDialogAdd = () => {
    nextTick(() => {
        //清空校验（清空表单校验结果，以便用户重新输入数据）
        ruleFormRefAdd.value.clearValidate()
    })
};
//查询当前角色拥有哪些功能权限，不要菜单
let checkedPerms = ref([])
let tree = ref(null)
//加载时设置当前角色的选中权限
const setCheckedKeys = () => {
    tree.value.setCheckedKeys(checkedPerms.value, false)
};
/**
 * 添加角色，数据提交(1.添加角色，2.保存授权)
 */
const handleSubmitAdd = (value) => {
    value.validate(valid => {
        if (valid) {
            //获取当前选中的复选框
            let checkedIds = tree.value.getCheckedKeys();
            let halfCheckedKeys = tree.value.getHalfCheckedKeys();
            console.log(`输出全选选复选框：` + checkedIds)
            console.log(`输出半选状态框Id：` + halfCheckedKeys)
            const data = {
                sysRole: rolesAdd,
                roleId: rolesAdd.roleId,
                menuIds: [...halfCheckedKeys, ...checkedIds]
            }
            insertRole(data)
            ElMessage.success(`添加成功`)
            handleClose()
        } else {
            ElMessage.error("请根据提示填写完整表单")
        }
    })

}

//取消按钮，关闭弹窗
const Visible = () => {
    Object.assign(rolesAdd, resetFormAdd)
    emit('close-dialog')
    clearSelections()
}
//关闭弹窗，处理数据
const handleClose = () => {
    Object.assign(rolesAdd, resetFormAdd)
    emit('close-dialog')
    clearSelections()
}
// 清除选中的复选框
const clearSelections = () => {
    const treeInstance = tree.value;

    if (treeInstance) {
        // 清空已选中的节点
        treeInstance.setCheckedKeys([]);

        // 清空已展开的节点
        treeInstance.store._expandedKeys = [];
        // 确保 nodesMap 是一个对象
        const nodesMap = treeInstance.store.nodesMap || {};
        Object.keys(nodesMap).forEach(key => {
            const node = nodesMap[key];
            node.expanded = false;
        });
    }
};

</script>

<style scoped></style>
